/***********************************************************
* 
*     File attach:  people.cpp
* 
*        Author:  Algolc
* 
*          mail:  17360224@qq.com
* 
*  Created Time:  Wed 08 Aug 2018 02:58:03 PM CST
* 
***********************************************************/

#include <stdlib.h>
#include <stdio.h>
#include "People.pb.h"

template <typename T>
using RepeatedField = google::protobuf::RepeatedPtrField<T>;

//普通删除, 根据attach来删除相应的数据
int removeSkill(const std::string& attach, People& peo) {
    RepeatedField<Skill>::const_iterator iter = peo.mutable_skill()->begin();
    for (; iter != peo.mutable_skill()->end(); ++iter) {
        if (iter->attach() == attach) {
            peo.mutable_skill()->erase(iter);
            return 0;
        }
    }
    return 0;
}

//使用auto自动定义响应的变量类型
int removeSkill_1(const std::string& attach, People& peo) {
    auto iter = peo.mutable_skill()->begin();
    for (; iter != peo.mutable_skill()->end(); ++iter) {
        if (iter->attach() == attach) {
            peo.mutable_skill()->erase(iter);
            return 0;
        }
    }
    return 0;
}

//已知要删除的数据index, 删除对应的repeated数据
template <typename T>
int removeRepeated(int index, T* repField) {
    //这里传进来的参数都要是repeated类型的
    auto iter = repField->begin(); //auto在这里是RepeatedField<Skill>::iterator 类型
    iter += index;
    if (iter != repField->end()) {
        repField->erase(iter);
        return 0;
    }
    
    return -1;
}

int main() {
    People peo;
    peo.set_age(27);
    peo.set_dog("赵思博");
    
    Skill* skill = peo.add_skill();
    skill->set_attach("江户36散手");
    skill->set_level(2);

    skill = peo.add_skill();
    skill->set_attach("左右互搏之术");
    skill->set_level(118);

    skill = peo.add_skill();
    skill->set_attach("铁裆功");
    skill->set_level(17);

    skill = peo.add_skill();
    skill->set_attach("缩阳入腹");
    skill->set_level(2000);

    printf("%s\n", peo.Utf8DebugString().c_str());
    
    removeRepeated(2, peo.mutable_skill());
    printf("%s\n", peo.Utf8DebugString().c_str());
    return 0;
}
